/**
 * @author:cloud.lg
 * @date:2021.3.26
 * @description:这里提供请求方法和定义基本拦截器行为
 */
import axios from 'axios'
import router from '@/router/routes'
import QS from 'qs'
import store from '@/store'
import { getStore } from '@/utils/util'
import { apiUrl } from '@/utils/env'
import Element from 'element-ui'

const timeout = '5000';
const withCredentials = false;

const getToken = () => {
    //TODO
    let share = JSON.parse(getStore('vuex')) || {};
    if (share.token) {
        return share.token;
    } else {
        return '';
    }
};

//响应拦截器
axios.interceptors.response.use(
    success => {
        //TODO
        if (success.data.code !== 200) {
            if (success.data.code === 401) {
                Element.Message({
                    message: success.data.msg,
                    type: 'error'
                })
                router.replace({
                    name: 'login',
                    query: { redirect: router.currentRoute.fullPath }
                });
            } else {
                Element.Message({
                    message: success.data.msg,
                    type: 'error'
                })
            }
        }
        return success;
        switch (success.data.code) {
            case 401:
                Element.Message({
                    message: success.data.msg,
                    type: 'error'
                })
                router.replace({
                    name: 'login',
                    query: { redirect: router.currentRoute.fullPath }
                });
                console.warn('the token expired!');
                break;
            case !500:
                Element.Message({
                    message: success.data.msg,
                    type: 'error'
                })
                break;

        }
        return success;
    },
    error => {
        if (error.data) {
            switch (error.data.code) {
                case 404:
                    console.warn('wrong request url Or params!')
                    break;
            }
        }
        return Promise.reject(error.response.data)
    });


/**
 * @method post请求
 * @param {string} url   : 请求的地址
 * @param { any  } params: 请求的参数
 * @param {string} type  : 请求的方式
 *
 * */
const post = (url, params = {}, type) => {
    /*if(getToken()){
    	params.token = getToken()
    }*/
    // for (var key in params) {
    //     if (!params[key] && params[key] !== 0) {
    //         delete params[key]
    //     }
    // }
    "qs" === type && (params = QS.stringify(params))
    "json" === type && (params = JSON.stringify(params))
    var headersData = {
        'Content-Type': 'application/json; charset=UTF-8'
    }
    if (url !== '/login') {
        headersData.Authorization = getToken()
    }
    return new Promise((resolve, reject) => {
        axios({
                method: 'post',
                url: url,
                baseURL: apiUrl,
                // timeout: timeout,
                withCredentials: withCredentials,
                data: params,
                headers: headersData
            })
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}


/**
 * @method get请求
 * @param {string} url   : 请求的地址
 * @param { any  } params: 请求的参数
 *
 * */
const get = (url, params = {}) => {
    // for (var key in params) {
    //     if (!params[key] && params[key] !== 0) {
    //         delete params[key]
    //     }
    // }
    var headersData = {
        'Content-Type': 'application/json; charset=UTF-8'
    }
    if (url !== '/login') {
        headersData.Authorization = getToken()
    }
    return new Promise((resolve, reject) => {
        /*if(getToken()){
  		params.token = getToken()
  	}*/
        axios({
                method: 'get',
                url: url,
                baseURL: apiUrl,
                // timeout: timeout,
                withCredentials: withCredentials,
                params: params,
                headers: headersData
            })
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}

/**
 * @method fetch请求
 * @param {string} url   : 请求的地址
 * @param { any  } params: 请求的参数
 * @param {string} type  : 请求的方式
 *
 * */
const fetch = (url, params = {}, type, method) => {
    "qs" === type && (params = QS.stringify(params))
    "json" === type && (params = JSON.stringify(params))
    var headersData = {
        'Content-Type': 'application/json; charset=UTF-8'
    }
    if (url !== '/login') {
        headersData.Authorization = getToken()
    }
    return new Promise((resolve, reject) => {
        axios({
                method: method,
                url: url,
                baseURL: apiUrl,
                // timeout: timeout,
                withCredentials: withCredentials,
                data: params,
                headers: headersData
            })
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}

export {
    get,
    post,
    fetch
}